﻿using System.Collections;
using UnityEngine;
using UnityEngine.UI;

public class GameController : Singleton<GameController> {

    public GameObject mGameOver;
    public GameObject LevelFinish;
    public GameObject ChestParent;
    public int totalSecond;
    public Text TimeBoard;
    [Range(0,1f)]
    public float LimitRate;
    public bool GameRunning = true;

    private int chestDestory;
    private int timeCount;
    private const string timeFormat = "剩余时间: {0}";

    public void Start()
    {
        StartCoroutine(timer());
    }

    public void GameOver()
    {
        GameRunning = false;
        mGameOver.SetActive(true);
    }

    public void Restart()
    {
        UnityEngine.SceneManagement.SceneManager.LoadScene("Main");
    }

    public void ChestDestory()
    {
        chestDestory++;
    }

    public void Finish()
    {
        GameRunning = false;
        LevelFinish.SetActive(true);
        Debug.Log("chest destory " + chestDestory);
        int count = ChestParent.transform.childCount;
        float rate = (float)chestDestory / (float)count;
        Debug.Log("rate is " + rate);
        Debug.Log("target rate is " + LimitRate);
        if(rate >= LimitRate)
        {
            UnityEngine.SceneManagement.SceneManager.LoadScene("VideoGameScene");
        }
    }

    private IEnumerator timer()
    {
        TimeBoard.text = string.Format(timeFormat, formatTime(totalSecond - timeCount));
        while (GameRunning)
        {
            yield return new WaitForSeconds(1f);
            timeCount++;
            TimeBoard.text = string.Format(timeFormat, formatTime(totalSecond - timeCount));
            if (totalSecond <= timeCount)
                GameOver();
        }        
    }

    private string formatTime(int second)
    {
        string format = "";
        int minute = second / 60;
        int sec = second % 60;
        if(minute < 10)
        {
            format += "0" + minute + ":";
        }
        else
        {
            format += minute + ":";
        }
        if(sec < 10)
        {
            format += "0" + sec;

        }
        else
        {
            format += sec;
        }
        return format;
    }
}
